<?php declare(strict_types=1);


namespace App\Services\Quota;

use App\Services\Pay\GuoTonXinYi\Mch;
use App\Services\Pay\ResultVo;
use Illuminate\Support\Facades\Log;

class GtxyQuotaService implements GetQuotaInterface
{

    protected function __construct()
    {

    }

    protected static $instance;

    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getQuota(string $mchNo, array $config): array
    {
        $resData = [
            'company_code' => $config["company"],
            'mch_id' => $mchNo,
            'start_date' => "",
            'end_date' => "",
            'quota' => 0
        ];
        $resultVo = Mch::queryActSubDetail($mchNo, [
            "orgId" => $config["orgId"],
            "key" => $config["key"],
        ]);
        if ($resultVo->getCode() != $resultVo->codeMap["ok"]) {
            return $resData;
        }
        $quotaItems = $resultVo->getData();
        $quota = 0;
        $start_date = $end_date = "";
        foreach ($quotaItems as $item) {
            if ($item["status"] == 0) {
                continue;
            }
            //当月额度
            $nowDay = date("Ymd", time());
            if ($nowDay < date('Ymd', strtotime($item['beginDate']))) {
                continue;
            }
            if ($nowDay > date('Ymd', strtotime($item['endDate']))) {
                continue;
            }
//            $quota = $item["txamtMonthSubsidy"] - $item["subMonthTxamtResidue"];
            $quotaAll = (float)$item["monthTotalSubidy"];
            if (empty($quotaAll)) {
                continue;
            }
            if (date('Ym', strtotime($item['beginDate'])) == date("Ym", time())) {
                $quota = (float)$item["remainMonthTotalSubidy"];
            } else {
                $quota = (float)$item["surplusTotalSubsidy"];
            }
            if (empty($quota)) {
                continue;
            }
            $start_date = date("Ymd", strtotime($item["beginDate"]));
            $end_date = date("Ymd", strtotime($item["endDate"]));
        }
        $resData = [
            'company_code' => $config["company"],
            'mch_id' => $mchNo,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'quota' => $quota
        ];
        Log::channel("quota")->info("queryActSubDetail", [
            "quotaItems" => $quotaItems,
            "resData" => $resData
        ]);
        return $resData;
    }

}